<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true">
        <el-form-item>
          <el-input v-model="keyword" placeholder="请输入关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="keywordQuery" >查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd" >新增</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="onsale" >上架</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="danger" @click="offsale" >下架</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <el-table :data="pets" highlight-current-row v-loading="listLoading" @selection-change="selsChange"
              style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="name" label="宠物名称" width="100" sortable>
      </el-table-column>
      <el-table-column prop="costprice" label="成本价" width="90" sortable>
      </el-table-column>
      <el-table-column prop="saleprice" label="市场价" width="90" sortable>
      </el-table-column>
      <el-table-column prop="petType.name" label="宠物类型" width="100" sortable>
      </el-table-column>
      <el-table-column prop="state" label="状态" min-width="50" sortable>
        <template scope="scope">
          <span v-if="scope.row.state==0" style="color: red">下架</span>
          <span v-else-if="scope.row.state==1" style="color: green">上架</span>
          <span v-else style="color: orange">未上过架</span>
        </template>
      </el-table-column>
      <el-table-column  prop="resources" label="图片" width="300" sortable>
        <template scope="scope">
          <img :src="imgPrefix+scope.row.resources" width="50px">
        </template>
      </el-table-column>
      <el-table-column prop="onsaletime" label="上架时间" width="150" sortable>
      </el-table-column>
      <el-table-column prop="offsaletime" label="下架时间" width="150" sortable>
      </el-table-column>
      <el-table-column prop="shops.name" label="所属店铺" width="150" sortable>
      </el-table-column>
      <el-table-column prop="user.username" label="领养人" width="100" sortable>
      </el-table-column>
      <el-table-column prop="searchMasterMsgId" label="宠物来源" min-width="100" sortable>
        <template scope="scope">
          <span v-if="scope.row.searchMasterMsgId==null" style="color: orange">来自店铺饲养</span>
          <span v-else style="color: darkmagenta">来自寻主消息</span>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)" >编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)" >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="pageSize"
                     :total="totals" :current-page="currentPage" style="float:right;">
      </el-pagination>
    </el-col>

    <!--编辑界面-->
    <el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false">
      <el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
        <el-form-item label="宠物名称" >
          <el-input v-model="saveForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="成本价" >
          <el-input v-model="saveForm.costprice" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="销售价" >
          <el-input v-model="saveForm.saleprice" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="宠物类型">
          <el-cascader v-model="saveForm.typeId"
                       :options="petTree"
                       :props="{
            checkStrictly: true,
            label: 'name',
            value: 'id'
          }"
                       clearable>
          </el-cascader>
        </el-form-item>
        <el-form-item prop="logo" label="店铺Logo">
          <el-upload
              class="upload-demo"
              action="http://localhost:8080/fastDfs/"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              :file-list="fileList"
              list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="所属店铺">
          <el-select v-model="saveForm.shopId" placeholder="请选择">
            <el-option
                v-for="item in shops"
                :label="item.name"
                :value="item.id">
              <span style="float: left">{{ item.name }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="简介" prop="intro">
          <!-- v-if="saveForm.petDetail" 修改v-model绑定对象报错问题，v-if对需要显示的数据判断下 -->
          <quill-editor  v-model="saveForm.petDetail.intro" v-if="saveForm.petDetail" :options="quillOption">
          </quill-editor>
        </el-form-item>
        <el-form-item label="领养须知" prop="orderNotice" >
          <quill-editor  v-model="saveForm.petDetail.adoptNotice" v-if="saveForm.petDetail" :options="quillOption">
          </quill-editor>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
      </div>
    </el-dialog>

  </section>
</template>

<script>
//引入富文本资源
import { quillEditor } from "vue-quill-editor"; //调用编辑器
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';
import quillConfig from '../../common/js/quill-config';

export default {
  data() {
    return {

      //文件上传相关数据
      fileList: [],

      quillOption: quillConfig,

      pets: [],
      totals: 0,
      currentPage: 1,
      pageSize: 5,
      listLoading: false,
      sels: [],//列表选中列
      shops: [],
      //显示部门树
      petTree:[],
      keyword: '',
      title: '',
      imgPrefix:'http://123.207.27.208',

      saveFormVisible: false,//编辑界面是否显示
      saveLoading: false,
      saveFormRules: {
        sn: [
          {required: true, message: '请输入编号', trigger: 'blur'}
        ],
        name: [
          {required: true, message: '请输入姓名', trigger: 'blur'}
        ]
      },
      //编辑界面数据
      saveForm: {
        id: null,
        name: '',
        costprice:'',
        saleprice:'',
        typeId:null,
        resources:'',
        state: 1,
        offsaletime: '',
        createtime: '',
        shopId: null,
        userId: null,
        petDetail:{  //与后端实体类一致
          intro: '',
          adoptNotice: ''
        }

      },

      addFormVisible: false,//新增界面是否显示
      addLoading: false,
      addFormRules: {
        name: [
          {required: true, message: '请输入姓名', trigger: 'blur'}
        ]
      },
    }
  },
  //富文本组件
  components: {
    quillEditor
  },
  methods: {
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getPets();
    },
    keywordQuery() {
      //防止当前页不在第一页的时候 通过关键字查询出现 当前页没有数据的情况
      this.currentPage = 1;
      this.getPets();
    },
    //获取用户列表
    getPets() {
      let para = {
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        keyword: this.keyword
      };
      this.listLoading = true;//显示加载框
      this.$http.post("pet", para).then(res => {
        //隐藏加载框/忙等框
        this.listLoading = false;
        //给totals赋值 - 计算分页栏
        this.totals = res.data.totals;
        //赋值分页数据 - 显示当前页的分页数据
        this.pets = res.data.data;
      }).catch(res => {
        this.$message.error('系统繁忙，请稍后再试')
      });

    },
    //删除
    handleDel: function (index, row) {
      //elementUi提供的确认框-点击确认之后执行then里的代码，点击取消执行cath中的代码
      this.$confirm('您确认删除该记录吗?', '警告', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;//显示加载框
        this.$http.delete("/pet/" + row.id).then(res => {
          this.listLoading = false;//关闭加载框
          if (res.data.success) {
            this.$message.success("操作成功");//提示成功
            var totalPage = Math.ceil(this.totals/this.pageSize);
            if (this.currentPage==totalPage &&(this.totals-1)%this.pageSize==0 && this.currentPage!=1){
              this.currentPage--;
            }
            this.getPets();
          } else {
            this.$message.error("系统错误,请联系管理员或稍后重试!!!")//后端错误走这里--500
          }
        }).catch(res => {
          this.$message.error("连接后台失败,请联系管理员"); //前端错误走这里-404,400
        })
      }).catch(() => {
        // this.$message.error("连接后台失败,请联系管理员"); //前端错误走这里-404,400
      });
    },
    //批量删除
    selsChange: function (sels) {
      this.sels = sels;
    },
    batchRemove: function () {
      var ids = this.sels.map(item => item.id);
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        //NProgress.start();
        this.$http.patch("/pet", ids).then(res => {
          this.listLoading = false;
          if (res.data.success) {
            this.$message.success("操作成功");//提示成功
            this.currentPage = 1;
            this.getPets();
          } else {
            this.$message.error("系统错误,请联系管理员或稍后重试")
          }
        }).catch(res => {
          this.$message.error("连接后台失败,请联系管理员");
        })

      }).catch(() => {

      });
    },
    //显示编辑界面
    handleEdit: function (index, row) {
      this.saveFormVisible = true;
      this.saveForm = Object.assign({}, row);
      this.title = "修改";
      this.getManagers();
      this.getPetTree();
      this.fileList=[];
      if(this.saveForm.resources){
        // 数组中每一个数据：/group1/M00/02/74/CgAIC2Ng84OAHp_6AAAKeULGgAs198.png
        var arr = this.saveForm.resources.split(",");
        for (let i = 0; i < arr.length ; i++) {
          var url = arr[i]
          this.fileList.push({"url":"http://123.207.27.208"+url});
        }
      }
    },
    //显示新增界面
    handleAdd: function () {
      this.saveFormVisible = true;
      this.saveForm = {
        id: null,
        name: '',
        costprice:'',
        saleprice:'',
        typeId:'',
        state: 1,
        resources:'',
        offsaletime: '',
        createtime: '',
        shopId: null,
        userId: null,
        petDetail:{  //与后端实体类一致
          intro: '',
          adoptNotice: ''
        }
      };
      this.title = "添加";
      this.getManagers();
      this.getPetTree();
      this.fileList = [];
    },
    //编辑
    saveSubmit: function () {
      this.$refs.saveForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.saveLoading = true;
            //NProgress.start();
            let para = Object.assign({}, this.saveForm);
            /**
             * 解决级联框不能选择部门
             * @type {null|*}
             */
                //1.不修改上级部门，没有点级联框 :2
                //2.不修改上级部门，点级联框选择过其他部门:[2]
                //3.去掉上级部门:[]
                //4.[3,9,12]
                //5.null
            var isArr = para.typeId;
            if (Array.isArray(isArr)){
              if (isArr.length==0){
                para.typeId = null;
              } else {
                para.typeId = isArr[isArr.length-1];
              }
            }
            this.$http.put("/pet", para).then(res => {
              this.saveLoading = false;//关闭加载框
              this.saveFormVisible = false;//关闭对话框
              if (res.data.success) {
                this.getPets();
              } else {
                this.$message.error("系统错误,请联系管理员或稍后重试");
              }
            }).catch(res => {
              this.$message.error("系统错误,请联系管理员或稍后重试");
            })
          });
        }
      });
      //处理fileList
      this.fileList = [];
      if (this.saveForm.resources){
        var arr = this.saveForm.resources.split(",");
        for (let i = 0; i < arr.length; i++) {
          var url = arr[i];
          this.fileList.push({"url":"http://123.207.27.208"+url});
        }
      }
    },
    getManagers() {
      this.$http.get("/shop").then(res => {
        this.shops = res.data;
      })
    },
    getPetTree() {
      this.$http.get("/petType/petTree").then(res => {
        this.petTree = res.data;
      })
    },
    //文件上传的业务逻辑
    handleSuccess(response, file, fileList){
     var url = response.resultObj;
      if (this.saveForm.resources){
        this.saveForm.resources = this.saveForm.resources+","+url;
      }else {
        this.saveForm.resources = url;
      }
      //2.处理fileList
      this.fileList = [];
      if (this.saveForm.resources){
        var arr = this.saveForm.resources.split(",");
        for (let i = 0; i < arr.length; i++) {
          var url = arr[i];
          this.fileList.push({"url":"http://123.207.27.208"+url});
        }
      }
    },
    //文件删除的业务逻辑
    handleRemove(file, fileList) {
      var filePath =file.url;
      filePath = filePath.substring(filePath.indexOf("/group1"));
      this.$http.delete("/fastDfs?path="+filePath)
          .then(res=>{
            if(res.data.success){
              this.$message({
                message: '删除成功!',
                type: 'success'
              });
            }else{
              this.$message({
                message: '删除失败!',
                type: 'error'
              });
            }
          })
      //1.处理resources：假如resources="url1,url2,url3,url4",现在删除一张图片url2。resources="url1,url3,url4"
      if (this.saveForm.resources){
        var arr = this.saveForm.resources.split(",");
        for (let i = 0; i < arr.length; i++) {
          var url = arr[i];
          if (url == filePath){
            arr.splice(i,1);
            break;
          }
        }
        this.saveForm.resources = arr.join(",");
      }
      //2.处理fileList
      this.fileList = [];
      if (this.saveForm.resources){
        var arr = this.saveForm.resources.split(",");
        for (let i = 0; i < arr.length; i++) {
          var url = arr[i];
          this.fileList.push({"url":"http://123.207.27.208"+url});
        }
      }
    },
    //图片预览
    handlePreview(file) {
      console.log(file);
    },
    onsale(){
      if (this.sels.length<1){
        this.$message.warning("请选择需要上架的宠物!")
        return;
      }
      var ids = this.sels.map(item => item.id);
      this.$confirm('确认上架？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        //NProgress.start();
        this.$http.patch("/pet/onsale", ids).then(res => {
          this.listLoading = false;
          if (res.data.success) {
            this.getPets();
          } else {
            this.$message.error("系统错误,请联系管理员或稍后重试")
          }
        }).catch(res => {
          this.$message.error("连接后台失败,请联系管理员");
        })

      }).catch(() => {

      });
    },
    offsale(){
      if (this.sels.length<1){
        this.$message.warning("请选择需要下架的宠物!")
        return;
      }
      var ids = this.sels.map(item => item.id);
      this.$confirm('确认下架？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        //NProgress.start();
        this.$http.patch("/pet/offsale", ids).then(res => {
          this.listLoading = false;
          if (res.data.success) {
            this.getPets();
          } else {
            this.$message.error("系统错误,请联系管理员或稍后重试")
          }
        }).catch(res => {
          this.$message.error("连接后台失败,请联系管理员");
        })

      }).catch(() => {

      });
    }

  },
  mounted() {
    this.getPets();
  }
}

</script>

<style scoped>

</style>